<template>
    <div class="song-audio">
        <audio id="player"
               :src='src'
               controls="controls"
               preload="true"
               @canplay="startPlay"
               @ended="ended"></audio>
    </div>
</template>

<script>
    import {mapGetters} from 'vuex'

    export default {
        name: 'song-audio',
        computed: {
            ...mapGetters(['id', 'url', 'isPlay'])
        },
        data() {
            return {
                src: ''
            }
        },
        watch: {
            isPlay() {
                this.togglePlay()
            },
            url() {
                this.src = this.url
            }
        },
        methods: {
            //获取链接后准备播放
            startPlay() {
                let player = document.querySelector('#player')
                player.play()
            },
            //播放完成后触发
            ended() {
                this.isPlay = false
            }, togglePlay() {
                let player = document.getElementById('player')
                if (this.isPlay) {
                    player.play()
                } else {
                    player.pause()
                }
            }

        }
    }
</script>

<style scoped>
    .song-audio {
        display: none;
    }
</style>